const User = require('../../model/User');
const errors = require('../../errors');
const Validate = require('../../util/baseUtil/Validate');
const LoginUtil = require('../../util/businessUtil/LoginUtil');
const crypto = require('crypto')
const LogUtil = require('../../util/baseUtil/LogUtil')
const moment = require('moment')
const AdminUser = require('../../model/AdminUser')
const mongoose = require('../../config/db/mongo');
const request = require('request')
var ObjectId = mongoose.Types.ObjectId;
const NewPrivateuser = require('../../model/Newprivateuser')
const Privateuser = require('../../model/Privateuser')
const MyPrivateAccount = require('../../model/MyPrivateAccount')
const Chatlistuser = require('../../model/Chatlistuser')

module.exports = {

    //用户CRUD

    getOneUser: async (req, res, next) => {
        try {
            let myAccounts = await MyPrivateAccount.find({}).exec()
            let accountList = []
            accountList = myAccounts.map(e=>{return e.uid})
            let newPrivateuser = await NewPrivateuser.findOne({ _id: req.body.id, isDelete:{$ne:1} }).exec()
            // newPrivateuser.updatetime = new Date()
            if(newPrivateuser.isClicked == 0){
                newPrivateuser.firstClickUser = [{staff:req.session.user._id,date:new Date()}]
                newPrivateuser.isClicked = 1
            }
            newPrivateuser.allClickUser.push({staff:req.session.user._id,date:new Date()})
            await newPrivateuser.save()
            let privateuser = await Privateuser.find({isDelete: {$ne:1},uid:newPrivateuser.uid}).sort({firstchprivatedate:-1}).exec()
            let result = {}
            result.privateuser = newPrivateuser
            result.detail = privateuser
            result.accounts = myAccounts
            return res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },

    getOneChat: async (req, res, next) => {
        try {
            let myAccounts = await MyPrivateAccount.find({}).exec()
            let accountList = []
            accountList = myAccounts.map(e=>{return e.uid})
            let chatlistuser = await Chatlistuser.findOne({ _id: req.body.id, isDelete:{$ne:1} }).exec()
            // chatlistuser.updatetime = new Date()
            if(chatlistuser.isClicked == 0){
                chatlistuser.firstClickUser = [{staff:req.session.user._id,date:new Date()}]
                chatlistuser.isClicked = 1
            }
            chatlistuser.allClickUser.push({staff:req.session.user._id,date:new Date()})
            await chatlistuser.save()
            let privateuser = await Privateuser.find({isDelete: {$ne:1},uid:chatlistuser.uid}).exec()
            let result = {}
            result.privateuser = chatlistuser
            result.detail = privateuser
            result.accounts = myAccounts
            return res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },

    getuserlist: async (req, res, next) => {
        let option = {}
        option.isDelete = 0
        if (req.body.cellphone) {
            option.cellphone = new RegExp(req.body.cellphone)
        }
        if (req.body.name) {
            option.nickName = new RegExp(req.body.name, 'i')
        }
        if (req.body.startDate) {
            option.createdAt = { $gte: new Date(req.body.startDate) }
        }
        if (req.body.endDate) {
            option.createdAt = { $lte: new Date(req.body.endDate) }
        }
        if (req.body.startDate && req.body.endDate) {
            option.createdAt = { $gte: new Date(req.body.startDate), $lte: new Date(req.body.endDate) }
        }
        let count = await User.countDocuments(option).exec()
        let page = req.body.page || 1
        let pageSize = req.body.pageSize || count
        // let data = await User.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
        let data = await User.aggregate([
            {
                $match: option
            },
            {
                $sort: {
                    createdAt: -1
                }
            },
            {
                $skip: ((page - 1) * pageSize)
            },
            {
                $limit: pageSize
            },
            {
                $lookup: {
                    from: "member",
                    localField: 'openid',
                    foreignField: 'openid',
                    as: 'member'
                }
            },
            {
                $lookup: {
                    from: "userPoint",
                    localField: 'openid',
                    foreignField: 'openid',
                    as: 'userPoint'
                }
            }
        ]).exec()
        let result = {}
        result.total = count
        result.currentPage = page
        result.data = data
        result.pageSize = pageSize
        res.ok('获取成功', result)
    },

    changeOneUser: async (req, res, next) => {
        console.log(req.body)
        let user = await User.findOne({ _id: req.body.id, isDelete: 0 }).exec()
        let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
        let member = await Member.findOne({ openid: user.openid, isDelete: 0 }).exec()
        user.vip = req.body.vip
        if (req.body.vip === 0) {
            member.type = '普通会员'
            await member.save()
        } else if (req.body.vip === 1) {
            member.type = 'VIP会员'
            await member.save()
        }
        if (req.body.cellphone) {
            user.cellphone = req.body.cellphone
        }
        if (req.body.name) {
            user.name = req.body.name
        }
        if (req.body.birthday) {
            user.birthday = new Date(req.body.birthday)
        }
        if (req.body.email) {
            user.email = req.body.email
        }
        await user.save()
        if (req.body.point) {
            let userPoint = await UserPoint.findOne({ openid: user.openid, isDelete: 0 }).exec()
            if(parseInt(req.body.point)>parseInt(member.point)){
                let newManualChangePoint = new ManualChangePoint({
                    openid: user.openid,
                    unionID: user.unionID,
                    expenseDate: new Date(),
                    memo: "人工修改积分", //人工操作备注
                    amount: (parseInt(req.body.point)-parseInt(member.point)), // 变动的积分数量
                    type: 0, // 0 为加，1为减
                    isDelete: 0,
                    account: req.session.user._id,
                    originalPoints: parseInt(member.point),
                    currentPoints: parseInt(req.body.point)
                })
                await newManualChangePoint.save()
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    expenseDate: new Date(),
                    memo: "人工修改积分", //人工操作备注
                    amount: (parseInt(req.body.point)-parseInt(member.point)), // 变动的积分数量
                    type: 0, // 0 为加，1为减
                    isDelete: 0,
                    account: req.session.user._id,
                })
                await newPointHistory.save()
            }else if(parseInt(req.body.point)<parseInt(member.point)){
                let newManualChangePoint = new ManualChangePoint({
                    openid: user.openid,
                    unionID: user.unionID,
                    expenseDate: new Date(),
                    memo: "人工修改积分", //人工操作备注
                    manual: 1, // 1位人工，0为自动
                    amount: (parseInt(req.body.point)-parseInt(member.point)), // 变动的积分数量
                    type: 1, // 0 为加，1为减
                    isDelete: 0,
                    account: req.session.user._id,
                    originalPoints: parseInt(member.point),
                    currentPoints: parseInt(req.body.point)
                })
                await newManualChangePoint.save()
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    expenseDate: new Date(),
                    memo: "人工修改积分", //人工操作备注
                    manual: 1, // 1位人工，0为自动
                    amount: (parseInt(member.point)-parseInt(req.body.point)), // 变动的积分数量
                    type: 1, // 0 为加，1为减
                    isDelete: 0,
                    account: req.session.user._id,
                })
                await newPointHistory.save()
            }
            member.point = req.body.point
            userPoint.current = req.body.point
            if (req.body.point > userPoint.total) {
                userPoint.total = req.body.point
            }
            if (req.body.point >= 10000) {
                user.vip = 1
                member.type = 'VIP会员'
            }
            await member.save()
            await userPoint.save()
            wxPublicAccessToken.getAccessToken(function (token) {
                let data = {
                    "code": member.code,
                    "card_id": memberCardNumber,
                    "bonus": member.point
                }
                // console.log(data)
                request({
                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                    method: "POST",
                    timeout: 10000,
                    encoding: null,
                    json: data
                }, function (error, response, body) {
                    // console.log(error)
                })
            })
        }
        res.ok('修改成功', user)
    },

    getUserAddress: async (req, res, next) => {
        let data = await User.findOne({ _id: req.body.id, isDelete: 0 }, 'openid').exec()
        let addressData = await Address.findOne({ openid: data.openid }).exec()
        res.ok('获取成功', addressData)
    },

    getUserLastFour: async (req, res, next) => {
        let option = {}
        option.isDelete = 0
        if (req.body.cellphone) {
            option.cellphone = new RegExp(req.body.cellphone)
        }
        let user = await User.aggregate([
            {
                $match: option
            },
            {
                $lookup: {
                    from: "userPoint",
                    localField: 'openid',
                    foreignField: 'openid',
                    as: 'userPoint'
                }
            },
        ])
        user.forEach(e => {
            e.userPoint = e.userPoint[0]
        })
        res.ok('获取成功', user)
        // let user = await User.find({ lastFour: req.body.cellphone, isDelete: 0 }).exec()
        // if (user.length == 0) {
        //     let user = await User.find({ cellphone: new RegExp(req.body.cellphone), isDelete: 0 }).exec()
        //     res.ok('获取成功', user)
        // } else {
        //     res.ok('获取成功', user)
        // }
    },

    userLogin: async (req, res, next) => {
        console.log('login')

        //auth_type 登录方式 1微信公众号登录 2微信小程序登录 3.账号密码登录
        let auth_type = parseInt(req.body.auth_type);

        if (Validate.isEmpty(auth_type) || !Validate.isInteger(auth_type)) {
            return next(new errors.ValidationError('auth_type错误'), { auth_type: auth_type })
        }

        switch (auth_type) {
            // case 1: {
            //     if (!Validate.isEmpty(req.signedCookies.user_id)) {
            //         LoginUtil.wxPublicWebCommonAuth(req, res, next)
            //     } else {
            //         LoginUtil.wxPublicWebSeniorAuth(req, res, next)
            //     }
            //     break;
            // }
            // case 2: {
            //     LoginUtil.wxLiteSignIn(req, res, next);
            //     break;
            // }
            case 3:
                {
                    LoginUtil.commonLogin(req, res, next);
                    break;
                }
            default:
                {
                    return res.fail('登录失败,暂不支持此登录方式', { auth_type: auth_type })
                }
        }
    },

    userLoginOut: async (req, res, next) => {
        req.session.destroy()

        return res.ok("退出成功")
    },

    changePassword: async (req, res, next) => {
        try {
            let username = req.body.username;
            let password = req.body.password;
            if (Validate.isEmpty(username)) {
                return next(new errors.ValidationError("_id不能为空"))
            }
            if (Validate.isEmpty(password)) {
                return next(new errors.ValidationError("password不能为空"))
            }
            let md5 = crypto.createHash('md5');
            password = md5.update(password).digest('hex');
            console.log(req.body,md5,password)
            let result = await AdminUser.updateOne({account: username}, {password: password})
            return res.ok("用户密码更改成功", result)
        } catch (e) {
            next(e)
        }
    }

}